# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :user_cache.py
# @Time      :2022/6/7 0007 18:45
# @Author    :何胜利
import json
import random

import redis

from models.user import UserModel


class BaseCacheTTL():
    """缓存有效期  防止缓存雪崩，给过期时间加一个随机值"""
    TTL = 0
    MAX_DELTA = 10 * 60

    @classmethod
    def get_val(cls):
        return cls.TTL + random.randrange(0, cls.MAX_DELTA)


class UserProfileCacheTTL(BaseCacheTTL):
    """用户资料缓存时间  秒"""
    TTL = 30 * 60


class UserNewsCacheTTL(BaseCacheTTL):
    """用户爆款的文章"""
    TTL = 24 * 60 * 3


class UserCache():

    def __init__(self, user_id):
        self.rdb = redis.Redis(db=5)

        self.key = "user:{}:profile".format(user_id)
        self.user_id = user_id

    def get(self):
        """获取用户信息"""
        try:
            ret = self.rdb.get(self.key)
            print("redis中的key数据", ret)

            if not ret:
                user = UserModel.query.filter_by(uid=self.user_id).first()
                if user:
                    data = {
                        "mobile": user.mobile,
                        'user_name': user.user_name,
                        'gender': user.gender,
                        'profile_photo': user.profile_photo,
                        'is_media': user.is_media,
                        'introduction': user.introduction,
                        'certificate': user.certificate,
                        'article_count': user.article_count,
                        'following_count': user.following_count,
                        'fans_count': user.fans_count,
                        'like_count': user.like_count,
                        'account': user.account,
                        'create_date': str(user.create_date),
                    }
                    try:
                        self.rdb.setex(self.key, BaseCacheTTL.get_val(), json.dumps(data))
                        return json.dumps(data)
                    except Exception as e:
                        print("data写入报错信息", e)
                else:
                    return None

            else:
                return json.loads(ret.decode('utf-8'))
        except Exception as e:
            print("redis 获取失败信息", e)
            return None

    def post(self):
        """把用户信息写入redis缓存"""
        ret = self.rdb.get(self.key)
        if not ret:
            user = UserModel.query.filter_by(uid=self.user_id).first()
            if user:
                data = {
                    "mobile": user.mobile,
                    'user_name': user.user_name,
                    'gender': user.gender,
                    'profile_photo': user.profile_photo,
                    'is_media': user.is_media,
                    'introduction': user.introduction,
                    'certificate': user.certificate,
                    'article_count': user.article_count,
                    'following_count': user.following_count,
                    'fans_count': user.fans_count,
                    'like_count': user.like_count,
                    'account': user.account,
                    'create_date': str(user.create_date),
                }
                try:
                    self.rdb.setex(self.key, BaseCacheTTL.get_val(), json.dumps(data))
                    # return json.dumps(data)
                except Exception as e:
                    print("data写入报错信息", e)
            else:
                return None
        else:
            return '用户信息已经存在'

    def delete(self):
        try:
            self.rdb.delete(self.key)
        except Exception as e:
            print("redis删除缓存的错误信息", e)

    def determine_user_exists(self):
        """判断用户缓存是否存在"""
        try:
            ret = self.rdb.get(self.key)
        except Exception as e:
            print("写入日志{}".format(e))
            return None
        if not ret:
            # 用户在redis中不存在
            user = UserModel.query.filter_by(uid=self.user_id).first()
            if user:
                data = {
                    "mobile": user.mobile,
                    'user_name': user.user_name,
                    'gender': user.gender,
                    'profile_photo': user.profile_photo,
                    'is_media': user.is_media,
                    'introduction': user.introduction,
                    'certificate': user.certificate,
                    'article_count': user.article_count,
                    'following_count': user.following_count,
                    'fans_count': user.fans_count,
                    'like_count': user.like_count,
                    'account': user.account,
                    'create_date': str(user.create_date),
                }
                try:
                    self.rdb.setex(self.key, BaseCacheTTL.get_val(), json.dumps(data))
                    # return json.dumps(data)
                except Exception as e:
                    print("data写入报错信息", e)
        else:
            # 用户在缓存中粗存在
            user_dict = json.loads(ret.decode('utf-8'))
            ret = user_dict
            return ret
